<?php

/**
 * 	Prepare reading of SQL dump file and executing SQL statements
 * 		@param $sql_dump_file
 */
function apphp_db_install($sql_dump_file) {
	global $error_mg;
	global $username;
	global $password;
	global $database_prefix;
	global $password_encryption;
	global $db;
	
	$sql_array = array();
	$query = "";
	
	// get  sql dump content
	$sql_dump = file($sql_dump_file);
	
	// replace database prefix if exists
	$sql_dump = str_replace("<DB_PREFIX>", $database_prefix, $sql_dump);

	if(get_magic_quotes_gpc()){
		$sql_dump = str_replace("''''", "''", $sql_dump);
	}

	// add ";" at the end of file
	if(substr($sql_dump[count($sql_dump)-1], -1) != ";") $sql_dump[count($sql_dump)-1] .= ";";		
								
	// replace username and password if exists
	if(EI_USE_USERNAME_AND_PASWORD){
		$sql_dump = str_replace("<USER_NAME>", $username, $sql_dump);
		if(EI_USE_PASSWORD_ENCRYPTION){
			if($password_encryption == "AES"){
				$sql_dump = str_replace("<PASSWORD>", "AES_ENCRYPT('".$password."', '".EI_PASSWORD_ENCRYPTION_KEY."')", $sql_dump);
			}else if($password_encryption == "MD5"){
				$sql_dump = str_replace("<PASSWORD>", "MD5('".$password."')", $sql_dump);
			}else{
				$sql_dump = str_replace("<PASSWORD>", "AES_ENCRYPT('".$password."', '".EI_PASSWORD_ENCRYPTION_KEY."')", $sql_dump);				
			}
		}else{
			$sql_dump = str_replace("<PASSWORD>", "'".$password."'", $sql_dump);
		}
	}else{
		$sql_dump = str_replace("<USER_NAME>", "", $sql_dump);
		$sql_dump = str_replace("<PASSWORD>", "''", $sql_dump);
	}
	$sql_dump = str_replace("<ENCRYPTION_TYPE>", $password_encryption, $sql_dump);

	// encode connection, server, client etc.	
	if(EI_USE_ENCODING){
		$db->SetEncoding(EI_DUMP_FILE_ENCODING, EI_DUMP_FILE_COLLATION);
	}		
	
	foreach($sql_dump as $sql_line){
		$tsl = trim(utf8_decode($sql_line));
		if(($sql_line != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "?") && (substr($tsl, 0, 1) != "#")) {
			$query .= $sql_line;
			if(preg_match("/;\s*$/", $sql_line)){
				if(EI_MODE == "debug"){
					if(!$db->Query($query)){ $error_mg[] = $db->Error(); return false; }						
				}else{
					if(!@$db->Query($query)){ $error_mg[] = $db->Error(); return false; }
				}
				$query = "";
			}
		}
	}
	return true;
}


function apphp_db_select_db($database) {
  return mysql_select_db($database);
}

function apphp_db_query($query) {
  global $link;
  $res=mysql_query($query, $link);
  return $res;
}

?>